package common

import (
	"context"
	"os"
	"strings"
	"time"

	"gitee.com/jason_elva8325/micro-quickstart/config"
	"github.com/go-kit/kit/log"
	"github.com/go-kit/kit/sd/etcdv3"
)

// ServiceTransportType 服务注册的通讯协议自定义类型
type ServiceTransportType int

// 服务注册的通讯协议类型枚举
const (
	_ ServiceTransportType = iota
	GRPCTransport
	HTTPTransport
)

// ServiceRegistry 服务注册方法
func ServiceRegistry(conf *config.ConfigFile, sType ServiceTransportType, logger log.Logger) *etcdv3.Registrar {
	// 获取IP地址
	ipv4, err := NetInterfaceCheck()
	if err != nil {
		logger.Log(err, true)
		os.Exit(1)
	}

	// 创建服务注册对象
	var instanceKey, instanceValue string
	switch sType {
	case GRPCTransport:
		instanceKey = conf.Common.SRDPrefix + conf.Common.SvcName + "/GRPC/" + ipv4 + ":" + conf.GRPC.GRPCPort
		instanceValue = ipv4 + ":" + conf.GRPC.GRPCPort
	case HTTPTransport:
		instanceKey = conf.Common.SRDPrefix + conf.Common.SvcName + "/HTTP/" + ipv4 + ":" + conf.HTTP.HTTPPort
		instanceValue = "http://" + ipv4 + ":" + conf.HTTP.HTTPPort
	default:
		logger.Log("Unknown transport type to registry", true)
		os.Exit(1)
	}

	client, err := etcdv3.NewClient(context.Background(), strings.Split(conf.Common.SRDETCDServers, ","), etcdv3.ClientOptions{
		DialTimeout:   time.Second * 3,
		DialKeepAlive: time.Second * 3,
		CACert:        conf.Common.SRDETCDCaCert,
		Cert:          conf.Common.SRDETCDCert,
		Key:           conf.Common.SRDETCDKey,
	})
	if err != nil {
		logger.Log("Service regist to ETCD server fail", err)
		os.Exit(1)
	}

	registrar := etcdv3.NewRegistrar(client, etcdv3.Service{
		Key:   instanceKey,
		Value: instanceValue,
	}, logger)

	return registrar
}
